package com.pf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/9/6
 */
@Configuration
@ConditionalOnClass(RestTemplateProxy.class)
public class RestTemplateConfig {

    /**
     * 读超时时间
     */
    @Value("${rest.readTimeout}")
    private Integer readTimeout;

    /**
     * 链接超时时间
     */
    @Value("${rest.connectionTimeout}")
    private Integer connectionTimeout;

    @Autowired
    private RestTemplateProxy restTemplateProxy;


    @Bean
    public SimpleClientHttpRequestFactory httpClientFactory() {
        SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
        httpRequestFactory.setReadTimeout(readTimeout);
        httpRequestFactory.setConnectTimeout(connectionTimeout);
        if (restTemplateProxy.getEnabled()) {
            SocketAddress address = new InetSocketAddress(restTemplateProxy.getHost(), restTemplateProxy.getPort());
            Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
            httpRequestFactory.setProxy(proxy);
        }
        return httpRequestFactory;
    }

    @Bean
    public RestTemplate restTemplate(SimpleClientHttpRequestFactory httpClientFactory) {
        RestTemplate restTemplate = new RestTemplate(httpClientFactory);
        return restTemplate;
    }

    /**
     * 自定义测试接口超时时间
     *
     * @return
     */
    @Bean
    public RestTemplate restTemplateCustomTimeOut() {
        RestTemplate restTemplate = new RestTemplate();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpContextFactory(new CustomHttpContextFactory());
        requestFactory.setReadTimeout(3000);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }

}
